package com.yang.controller;

import org.apache.catalina.security.SecurityUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * @author yds
 * @program spring-boot-shiro
 * @description shiro控制的访问请求层
 * @create 2020-10-22 14:08
 **/
@Controller
public class ShiroController {

    @RequestMapping({"/", "index"})
    public String index(Model model) {
        model.addAttribute("msg", "hello shiro!");
        return "index.html";
    }

    @RequestMapping("/toLogin")
    public String login(Model model) {
        model.addAttribute("msg", "login");
        return "login.html";
    }

    @RequestMapping("/user/add")
    public String add(Model model) {
        return "/user/add.html";
    }

    @RequestMapping("/user/update")
    public String update(Model model) {
        return "/user/update.html";
    }
    @RequestMapping("/login")
    public String login(String userName,String password,Model model){
        //获取当前对象
        Subject subject = SecurityUtils.getSubject();
        //封装用户的登录数据-加密令牌
        UsernamePasswordToken token = new UsernamePasswordToken(userName, password);
        //登录令牌-执行登陆的方法，没有异常则ok
        try{
            subject.login(token);
            return "index";
        }catch (UnknownAccountException e){
            //用户名不存在
            e.printStackTrace();
            model.addAttribute("msg","用户名错误");
            return "login";
        }catch (IncorrectCredentialsException e){
            //密码问题
            e.printStackTrace();
            model.addAttribute("msg","密码错误");
            return "login";
        }
    }
    @RequestMapping("/unAuth")
    public String Unauthorized(Model model){
        model.addAttribute("msg","用户未授权");
        return "unauthorized";
    }
}